package sqls

import (
	"database/sql"
)
/**
	执行一句sql 实现增删改
 */
func ExecSql(sql string,db *sql.DB,params []interface{}) (int64,error){

	result,err := db.Exec(sql,params...)
	if err!=nil {
		return 0,err
	}
	affected, err := result.RowsAffected()
	if err!=nil {
		return 0,err
	}
	return affected,nil
}
/**
	执行一句sql，获取结果集（实现查询）
 */
func GetList(sql string,db *sql.DB) ([]map[string]interface{},error){
	rows,err := db.Query(sql)
	if err!= nil {
		return  nil,err
	}
	defer rows.Close()

	tableData := make([]map[string]interface{},0)
	columns, _ := rows.Columns()
	length := len(columns)
	//结果集
	values := make([]interface{}, length)
	//指针
	valuePtrs := make([]interface{}, length)
	for rows.Next() {
		for i := 0; i < length; i++ {
			valuePtrs[i] = &values[i]
		}
		rows.Scan(valuePtrs...)
		entry := make(map[string]interface{})
		for i, col := range columns {
			var v interface{}
			val := values[i]
			b, ok := val.([]byte)
			if ok {
				v = string(b)
			} else {
				v = val
			}
			entry[col] = v
		}
		tableData = append(tableData, entry)
	}
	return tableData,nil
}
